<template>
  <div class="data-bridge-create">
    <!-- <back-button back-url="/bridge">
      {{ tl('backDataBridge') }}
    </back-button> -->
    <div class="page-header-title">
      {{ tl('createBridge') }}
    </div>

    <el-row>
      <el-col :span="12">
        <el-steps :active="stepActive" finish-status="success">
          <el-step :title="tl('bridgeType')"> </el-step>
          <el-step :title="tl('configuration')"></el-step>
        </el-steps>
      </el-col>
    </el-row>
    <el-row class="config-body">
      <template v-if="stepActive === 0">
        <div class="part-header">
          {{ tl('chooseBridgeType') }}
        </div>
        <el-radio-group class="bridge-type-select" v-model="radioSelectedBridgeType">
          <el-row :gutter="28">
            <el-col v-for="item in bridgeTypeOptions" :key="item.label" :span="8">
              <el-radio class="bridge-type-item" :label="item.valueForRadio" border>
                <img
                  class="bridge-type-item-img"
                  height="80"
                  width="80"
                  :src="require(`@/assets/img/${item.value}.png`)"
                  :alt="item.label"
                />
                <div class="bridge-type-item-bd">
                  <div class="title">{{ item.label }}</div>
                  <span class="bridge-type-desc">{{ item.desc }}</span>
                </div>
              </el-radio>
            </el-col>
          </el-row>
        </el-radio-group>
      </template>
      <template v-if="stepActive === 1">
        <bridge-http-config
          v-if="chosenBridgeType === 'http'"
          v-model:tls="tlsParams"
          v-model="bridgeData"
        />
        <bridge-mqtt-config v-if="chosenBridgeType === 'mqtt'" v-model="bridgeData" />
      </template>
    </el-row>
    <el-row class="config-btn">
      <el-button
        size="small"
        type="primary"
        v-if="stepActive === 1"
        :loading="submitLoading"
        @click="submitCreateBridge"
      >
        {{ $t('Base.create') }}
      </el-button>
      <el-button
        type="primary"
        size="small"
        @click="goNextStep"
        v-if="stepActive < 1"
        :disabled="submitLoading"
      >
        {{ $t('Base.nextStep') }}
      </el-button>
      <el-button size="small" @click="--stepActive" v-if="stepActive > 0" :disabled="submitLoading">
        {{ $t('Base.backStep') }}
      </el-button>
      <el-button
        size="small"
        v-if="stepActive === 0"
        @click="$router.push({ name: 'data-bridge' })"
      >
        {{ $t('Base.cancel') }}
      </el-button>
    </el-row>
    <div></div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, Ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import BridgeHttpConfig from './BridgeHttpConfig.vue'
import BridgeMqttConfig from './BridgeMqttConfig.vue'
import { tlsConfig } from '@/types/ruleengine'
import { createBridge } from '@/api/ruleengine'
import _ from 'lodash'
import { useRouter } from 'vue-router'
import { ElMessage as M } from 'element-plus'
import { useBridgeTypeOptions } from '@/hooks/Rule/topology/bridge/useBridgeTypeValue'
import { BridgeType } from '@/types/enum'

export default defineComponent({
  components: { BridgeHttpConfig, BridgeMqttConfig },
  setup() {
    const tlsParamsDefault: tlsConfig = {
      enable: false,
      verify: 'verify_none',
      certfile: '',
      keyfile: '',
      cacertfile: '',
    }
    const stepActive = ref(0)
    const router = useRouter()
    const { t } = useI18n()
    const { bridgeTypeOptions, getTrueTypeObjByRadioValue } = useBridgeTypeOptions()
    const radioSelectedBridgeType = ref(bridgeTypeOptions[0].valueForRadio)
    const chosenBridgeType = ref(bridgeTypeOptions[0].value)
    const submitLoading = ref(false)
    const bridgeData = ref({})
    const tlsParams: Ref<tlsConfig> = ref(tlsParamsDefault)

    // watch(
    //   () => [_.cloneDeep(bridgeData.value), _.cloneDeep(tlsParams.value)],
    //   (val) => {
    //     console.log(val);
    //   }
    // );

    const handleTypeSelected = () => {
      const type = getTrueTypeObjByRadioValue(radioSelectedBridgeType.value)
      if (!type) {
        return
      }
      chosenBridgeType.value = type.value
      if (type.externalConfig) {
        bridgeData.value = { ...bridgeData.value, ..._.cloneDeep(type.externalConfig) }
      }
    }

    const goNextStep = () => {
      if (stepActive.value === 0) {
        handleTypeSelected()
      }
      stepActive.value += 1
    }

    const submitCreateBridge = async () => {
      let res
      submitLoading.value = true
      switch (chosenBridgeType.value) {
        case BridgeType.HTTP:
          res = await createBridge({
            ...bridgeData.value,
            ssl: { ...tlsParams.value },
            type: chosenBridgeType.value,
          }).catch(() => {})
          break
        case BridgeType.MQTT:
          res = await createBridge({
            ...bridgeData.value,
            type: chosenBridgeType.value,
          }).catch(() => {})
          break
      }

      if (res) {
        M({
          type: 'success',
          message: t('Base.createSuccess'),
        })
        router.push({ name: 'data-bridge' })
      }
      submitLoading.value = false
    }

    return {
      tl: (key: string) => t('RuleEngine.' + key),
      stepActive,
      goNextStep,
      bridgeTypeOptions,
      chosenBridgeType,
      radioSelectedBridgeType,
      submitLoading,
      tlsParams,
      bridgeData,
      submitCreateBridge,
    }
  },
})
</script>

<style lang="scss" scoped>
.config-btn {
  margin-top: 50px;
}

.el-radio.is-bordered {
  border-radius: 0px;
  padding: 0px 10px;
  min-width: 40%;
  border: 2px solid #e4e4e4;
  margin-top: 16px;
  height: unset;
  :deep(.el-radio__input) {
    display: none;
  }

  :deep(.el-radio__label) {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    padding: 0 0 0 80px;
    min-height: 80px;
    .title {
      margin-bottom: 4px;
      font-weight: bold;
      font-size: 14px;
      color: #000;
    }
    .bridge-type-desc {
      color: #0000007f;
      font-size: 12px;
      word-break: break-all;
      white-space: normal;
    }
  }
}

.config-body {
  flex-direction: column;
  margin-top: 30px;
  width: 70%;
}
.bridge-type-select {
  width: 100%;
}
.bridge-type-item {
  box-sizing: border-box;
  width: 100%;
}
.bridge-type-item-img {
  position: absolute;
  top: 0;
  left: 0;
}
</style>
